package dao;


import dao.exception.DAOException;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Parent DAO layer class<br/>
 * for init EntityManager and<br/>
 * define CRUD operation
 * User: kaiser
 * Date: 7/31/13
 * Time: 11:19 PM
 */
public abstract class DAO<T> {

    public static final int ONE_RECORD = 1;

    @PersistenceContext(unitName = "rssPool")
    protected EntityManager entityManager;

    /**
     * Get list of entities
     *
     * @return
     */
    abstract public List<T> getAll();

    /**
     * Persist entity to DB
     *
     * @param entity
     * @throws DAOException if entity is null
     */
    public void create(T entity) throws DAOException {
        if (notNull(entity)) {
            getEntityManager().merge(entity);
        }
    }

    /**
     * update entity
     *
     * @param entity to update
     * @throws DAOException if entity is null
     */
    public void update(T entity) throws DAOException {
        if (notNull(entity)) {
            getEntityManager().merge(entity);
        }
    }

    /**
     * Delete entity item
     *
     * @param entity to delete
     * @throws DAOException if entity is null
     */
    public void delete(T entity) throws DAOException {
        if (notNull(entity)) {
            T deletedApplicant = entity;
            if (!getEntityManager().contains(entity)) {
                deletedApplicant = getEntityManager().merge(entity);
            }

            getEntityManager().remove(deletedApplicant);
        }
    }

    /**
     * Check is entity not null
     *
     * @param entity entity item to check
     * @return true if entity object is not null
     * @throws DAOException if entity is null
     */
    protected boolean notNull(T entity) throws DAOException {
        if (entity == null) {
            throw new DAOException("Entity is NULL");
        }
        return true;
    }

    protected EntityManager getEntityManager() {
        return entityManager;
    }
}
